/* Prediction2.ado (STATA)
	Predict returns.
	by Ralph Koijen & Motohiro Yogo */

#delimit ;

program Prediction2;
args n;


/* Step 1: Predict equity returns in long sample */

u "../1 Data/SPX", clear;

/* Predict returns */

reg _ret Lmb, robust;

local c_Lmb = _b[Lmb];


/* Step 2: Predict exchange rate growth */

/* Load data */

u "../1 Data/Data4", clear;

/* Predict exchange rate growth */

qui reg _Gfx Lrealfx Icounterpar_*
	if counter_euro!="USA" & type==1 & Iycounter_euro, nocons cluster(year);

eststo _Gfx;

/* Save coefficients */

gen c_Lmb = -1/maturity if type==1;

gen c_Lrealfx = _b[Lrealfx] if type==1;

gen c_cons = 0 if type==1;

mata: c1 = st_matrix("e(b)");
mata: c1 = c1[1,1];
mata: Var_c1 = st_matrix("e(V)");
mata: Var_c1 = Var_c1[1,1];


/* Step 3: Predict LT debt returns */

/* Predict returns */

qui reg _ret Lmb Lrealfx Icounterpar_*
	if type==2 & Iycounter_euro, cluster(year);

eststo _ret2;

/* Save coefficients */

foreach var of varlist Lmb Lrealfx {;
	replace c_`var' = _b[`var'] if type==2;
};

replace c_cons = _b[_cons] if type==2;

mata: c2 = st_matrix("e(b)");
mata: c2 = c2[1,1..2];
mata: Var_c2 = st_matrix("e(V)");
mata: Var_c2 = Var_c2[1..2,1..2];


/* Step 4: Predict equity returns */

/* Impose coefficient restriction */

gen _ret_Lmb = _ret-`c_Lmb'*Lmb if type==3;

/* Predict returns */

qui reg _ret_Lmb Lrealfx Icounterpar_*
	if type==3 & Iycounter_euro, cluster(year);

eststo _ret3;

drop _ret_Lmb;

/* Save coefficients */

replace c_Lmb = `c_Lmb' if type==3;

replace c_Lrealfx = _b[Lrealfx] if type==3;

replace c_cons = _b[_cons] if type==3;

mata: c3 = st_matrix("e(b)");
mata: c3 = c3[1,1];
mata: Var_c3 = st_matrix("e(V)");
mata: Var_c3 = Var_c3[1,1];

/* Save coefficients and covariance matrix */

mata: mata matsave Prediction`n' c* Var_c*, replace;

/* Output table */

esttab, b(%8.2f) se(%8.2f) r2 obslast plain
	drop(Icounterpar_*) order(Lmb);

eststo clear;


/* Step 5: Construct expected returns */

/* Expected returns in USD */

gen Eret = c_Lmb*Lmb+c_Lrealfx*Lrealfx+c_cons;

/* Adjust expected returns to local currency */

egen Eret_LCU = total(Eret*(type==1 & Iycounterpart)), missing by(year country);

replace Eret = Eret-Eret_LCU;

drop Eret_LCU;

/* Label variables */

label var c_Lmb		"Expected return: Coefficient on Lmb";
label var c_Lrealfx	"Expected return: Coefficient on Lrealfx";
label var c_cons	"Expected return: Constant";

label var Eret		"Expected return";

/* Save data */

sort year country counterpart type;

save Prediction`n', replace;

end;
